package com.frp.client;

import com.frp.config.ConfigLoader;
import com.frp.config.FrpcConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * FRP客户端主应用类
 */
public class FrpcApplication {
    private static final Logger logger = LoggerFactory.getLogger(FrpcApplication.class);
    
    private FrpcConfig config;
    private ConnectionManager connectionManager;
    private HeartbeatManager heartbeatManager;
    private volatile boolean running = false;
    
    /**
     * 启动FRP客户端
     */
    public void start(String configFile) throws Exception {
        logger.info("启动FRP客户端...");
        
        // 加载配置
        try {
            config = ConfigLoader.loadFromFile(configFile);
            logger.info("配置加载成功");
        } catch (IOException e) {
            logger.error("加载配置文件失败: {}", e.getMessage());
            System.exit(1);
        }
        
        // 初始化组件
        initializeComponents();
        
        // 启动服务
        startServices();
        
        running = true;
        logger.info("FRP客户端启动成功");
    }
    
    /**
     * 停止FRP客户端
     */
    public void stop() {
        if (!running) {
            return;
        }
        
        logger.info("停止FRP客户端...");
        running = false;
        
        try {
            if (heartbeatManager != null) {
                heartbeatManager.stop();
            }
            
            if (connectionManager != null) {
                connectionManager.stop();
            }
            
            logger.info("FRP客户端已停止");
        } catch (Exception e) {
            logger.error("停止客户端时出错", e);
        }
    }
    
    /**
     * 初始化组件
     */
    private void initializeComponents() {
        logger.info("初始化组件...");
        
        connectionManager = new ConnectionManager(config);
        
        heartbeatManager = new HeartbeatManager(
            connectionManager,
            config.getCommon().getHeartbeatInterval(),
            config.getCommon().getHeartbeatTimeout()
        );
    }
    
    /**
     * 启动服务
     */
    private void startServices() throws Exception {
        logger.info("启动服务...");
        
        // 启动连接管理器
        connectionManager.start();
        
        // 启动心跳管理器
        heartbeatManager.start();
        
        // 添加关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
    }
    
    /**
     * 检查是否正在运行
     */
    public boolean isRunning() {
        return running;
    }
    
    /**
     * 获取配置
     */
    public FrpcConfig getConfig() {
        return config;
    }
    
    /**
     * 主函数入口
     */
    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("使用方法: java -jar java-frpc.jar <配置文件>");
            System.exit(1);
        }
        
        String configFile = args[0];
        FrpcApplication application = new FrpcApplication();
        
        try {
            application.start(configFile);
            
            // 保持主线程运行
            while (application.isRunning()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
            
        } catch (Exception e) {
            logger.error("启动失败", e);
            System.exit(1);
        }
    }
}